﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;

namespace Xceed.Silverlight.Data
{
  internal class TotalCountEnumerator<T> : AsyncParentEnumerator<T>
  {
    #region Static Fields

    private static readonly Guid JumpMoveAndFetchCallId = DataUtils.CreateCallId();
    private static readonly Guid GetTotalCountCallId = DataUtils.CreateCallId();

    #endregion

    #region Constructor

    internal TotalCountEnumerator( IAsyncEnumerator childEnumerator )
      : base( childEnumerator )
    {
    }

    #endregion

    public override JumpMoveAndFetchAsyncResult BeginJumpMoveAndFetch(
      JumpMoveAndFetchParameters parameters,
      AsyncCallback callback,
      object state )
    {
      JumpMoveAndFetchAsyncResult asyncResult = new JumpMoveAndFetchAsyncResult(
                                                  TotalCountEnumerator<T>.JumpMoveAndFetchCallId,
                                                  callback,
                                                  state,
                                                  parameters );
      DataSourceContext context = parameters.Context;

      asyncResult.AddDependentCall(
        ( cb, st ) => base.BeginJumpMoveAndFetch( parameters, cb, st ),
        ( par, iar ) => new DependentCallResult( base.EndJumpMoveAndFetch( ( JumpMoveAndFetchAsyncResult )iar ) ) );

      asyncResult.AddDependentCall(
        ( cb, st ) => this.BeginGetTotalCount( context, ( JumpMoveAndFetchResult<T> )st, cb, st ),
        ( par, iar ) => new DependentCallResult( this.EndGetTotalCount( iar ) ) );

      asyncResult.Start();

      return asyncResult;
    }

    public override JumpMoveAndFetchResult<T> EndJumpMoveAndFetch(
      JumpMoveAndFetchAsyncResult asyncResult )
    {
      asyncResult.ValidateCallEnd( TotalCountEnumerator<T>.JumpMoveAndFetchCallId );

      return asyncResult.GetCallResult<JumpMoveAndFetchResult<T>>();
    }

    protected override void Dispose( bool disposing )
    {
      m_disposed = true;

      base.Dispose( disposing );
    }

    private IAsyncResult BeginGetTotalCount(
      DataSourceContext context,
      JumpMoveAndFetchResult<T> dataResult,
      AsyncCallback callback,
      object state )
    {
      AsyncResult asyncResult = new AsyncResult(
                                  TotalCountEnumerator<T>.GetTotalCountCallId,
                                  callback,
                                  state );

      if( ( m_disposed )
        || ( dataResult == null )
        || ( dataResult.TotalCount != null ) )
      {
        asyncResult.StartSync( dataResult );
      }
      else
      {
        asyncResult.Start(
          ( cb, st ) => this.BeginCount( new CountParameters( context ), cb, st ),
          ( par, iar ) =>
          {
            CountResult countResult = this.EndCount( iar );
            if( ( countResult == null ) || ( countResult.Count == null ) )
              return new DependentCallResult( dataResult );

            JumpMoveAndFetchResult<T> newDataResult = new JumpMoveAndFetchResult<T>(
                                                        dataResult.SourcePosition,
                                                        dataResult.ApproximateMove,
                                                        dataResult.ExpectedMoveCount,
                                                        dataResult.ExpectedFetchCount,
                                                        dataResult.ActualMoveCount,
                                                        dataResult.FetchedItems,
                                                        dataResult.Result,
                                                        dataResult.EndPositionObject,
                                                        dataResult.EndPositionOffset,
                                                        countResult.Count );

            return new DependentCallResult( newDataResult );
          } );
      }

      return asyncResult;
    }

    private JumpMoveAndFetchResult<T> EndGetTotalCount( IAsyncResult asyncResult )
    {
      asyncResult.ValidateCallEnd( TotalCountEnumerator<T>.GetTotalCountCallId );

      return asyncResult.GetCallResult<JumpMoveAndFetchResult<T>>();
    }

    #region Private Fields

    private bool m_disposed; //false

    #endregion
  }
}
